package com.sojson.project.sys.role.controller;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sojson.config.exception.TransErrorCode;
import com.sojson.constant.Lock;
import com.sojson.project.sys.role.controller.param.verify.RoleParamVerify;
import com.sojson.project.sys.role.entity.dto.RoleDto;
import com.sojson.project.sys.role.entity.dto.RolePageDto;
import com.sojson.project.sys.role.entity.po.Role;
import com.sojson.project.sys.role.entity.vo.RoleVo;
import com.sojson.project.sys.role.service.RoleService;
import com.sojson.result.Result;
import com.sojson.util.lock.CustomLock;
import com.sojson.util.lock.LockUtil;
import com.sojson.util.param.ParamUtil;
import com.sojson.util.poi.ExcelUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 角色信息表控制器
 * 
 * @author liu
 * @date 2021-04-13
 */
@Api(tags = "角色信息表管理")
@RestController
@RequestMapping(value = "/sys/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 单条插入
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PostMapping("/save")
    @PreAuthorize("@ss.hasPermi('/sys/role/save')")
    @ApiOperation("给角色信息表添加一条数据")
    public Result<Boolean> save(@RequestBody Role dto) throws Exception {
        dto.insertInit();
        // 校验参数
        Result<Boolean> paramResult = RoleParamVerify.save(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        CustomLock lock = LockUtil.lock(Lock.ROLE_UPDATE);
        try {
            roleService.add(dto);
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }

        // 刷新权限
        roleService.refreshPerms();
        return Result.success();
    }

    /**
     * 通过id更新
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PutMapping(value = "/updateById")
    @PreAuthorize("@ss.hasPermi('/sys/role/updateById')")
    @ApiOperation("通过ID修改角色和角色菜单关联关系")
    public Result<Boolean> updateById(@RequestBody Role dto) throws Exception {
        dto.updateInit();
        // 校验参数
        Result<Boolean> paramResult = RoleParamVerify.updateById(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        CustomLock lock = LockUtil.lock(Lock.ROLE_UPDATE);
        try {
            roleService.update(dto);
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }

        // 刷新权限
        roleService.refreshPerms();
        return Result.success();
    }

    /**
     * 分页查询
     * 
     * @param dto
     * @return
     * @throws IOException 
     */
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermi('/sys/role/page')")
    @ApiOperation(value = "分页查询角色表数据", response = RoleVo.class)
    public Result<List<RoleVo>> page(RolePageDto dto) throws IOException {
        List<RoleVo> list = roleService.page(dto);
        return Result.success(list);
    }

    /**
     * 导出数据
     * 
     * @param dto
     * @throws Exception 
     */
    @GetMapping(value = "/export")
    @PreAuthorize("@ss.hasPermi('/sys/role/export')")
    @ApiOperation("导出角色")
    public void export(RoleDto dto) throws Exception {
        List<RoleVo> list = roleService.list(dto);
        ExcelUtil<RoleVo> excelUtil = new ExcelUtil<>(RoleVo.class);
        excelUtil.exportExcelOutFile(list, "角色列表");
    }

    /**
     * 通过id查询
     * 
     * @param id
     * @return
     * @throws IOException 
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("@ss.hasPermi('/sys/role/info/{id}')")
    @ApiOperation(value = "通过id查询角色角色表数据", response = RoleVo.class)
    public Result<RoleVo> info(@PathVariable String id) throws IOException {
        ParamUtil.verifyRoleIdExist(id);

        return Result.success(roleService.findById(id));
    }

    /**
     * 通过id列表删除
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @DeleteMapping("/remove")
    @PreAuthorize("@ss.hasPermi('/sys/role/remove')")
    @ApiOperation("通过id列表删除角色表数据")
    public Result<Boolean> remove(@RequestBody RoleDto dto) throws Exception {
        Set<String> ids = dto.getIds();
        if (ids == null || ids.size() == 0) {
            return Result.success();
        }
        ParamUtil.verifyRoleIdExist(ids);

        CustomLock lock = LockUtil.lock(Lock.ROLE_UPDATE);
        try {
            roleService.removeByIds(ids);
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }

        // 刷新权限
        roleService.refreshPerms();
        return Result.success();
    }

    /**
     * 状态修改
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PutMapping("/changeStatus")
    @PreAuthorize("@ss.hasPermi('/sys/role/changeStatus')")
    @ApiOperation("修改角色状态")
    public Result<Boolean> changeStatus(@RequestBody Role dto) throws Exception {
        // 校验参数
        Result<Boolean> paramResult = RoleParamVerify.updateStatus(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        CustomLock lock = LockUtil.lock(Lock.ROLE_UPDATE);
        try {
            Role role = new Role();
            role.setId(dto.getId());
            role.setStatus(dto.getStatus());
            roleService.updateStatus(role);
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }

        // 刷新权限
        roleService.refreshPerms();
        return Result.success();
    }

    /**
     * 修改保存数据权限
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PutMapping("/dataScope")
    @PreAuthorize("@ss.hasPermi('/sys/role/dataScope')")
    @ApiOperation("通过ID修改角色和角色部门关联关系")
    public Result<Boolean> dataScope(@RequestBody Role dto) throws Exception {
        // 校验参数
        Result<Boolean> paramResult = RoleParamVerify.updateById(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }
        if (!ParamUtil.isRoleIdExist(dto.getId())) {
            return Result.fail("角色权限不足");
        }

        dto.updateInit();
        CustomLock lock = LockUtil.lock(Lock.ROLE_UPDATE);
        try {
            roleService.authDataScope(dto);
        } finally {
            if (lock != null) {
                lock.unlock();
            }
        }

        // 刷新权限
        roleService.refreshPerms();
        return Result.success();
    }

}